﻿<%@ WebHandler Language="C#" Class="ContainerStepInfoDispatchHandler" %>
using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using System.Web.SessionState;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using DatabaseAccess.DBUtility;
using System.Threading.Tasks;

//Description: 工步派工页面处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2022-07-28
public class ContainerStepInfoDispatchHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonIBusiness uMESCommonbusiness = uMESBusinessFactory.instance.GetuLMSCommonObject();
    uLMSDispatchIBusiness uMESDispatchbusiness = uMESBusinessFactory.instance.GetuLMSDispatchObject();
    uLMSCommissioningIBusiness m_commissioning = uMESBusinessFactory.instance.GetuLMSCommissioning();
    uLMSContainerShipIBusiness m_ontainerShipObject = uMESBusinessFactory.instance.GetuLMSContainerShipObject();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "缓存过期了，请重新登录", Result = false }));
                return;
            }
            var action = context.Request.Form["action"].ToString();
            switch (action)
            {
                case "GetContainerStepInfoDispatchList"://工步派工批次主数据
                    GetContainerStepInfoDispatchList(context);
                    break;
                case "GetRBContainerDetails"://工步派工批次详细（热表）
                    GetRBContainerDetails(context);
                    break;
                case "GetContainerDetails"://工步派工批次详细（未启用）
                    GetContainerDetails(context);
                    break;
                //工步派工弹窗
                case "GetInitData"://工步派工弹窗初始化页面
                    GetInitData(context);
                    break;
                case "GetOperator"://获取操作工
                    GetOperator(context);
                    break;
                case "GetResource"://获取设备
                    GetResource(context);
                    break;
                case "GetStepInfoList"://获取工步列表
                    GetStepInfoList(context);
                    break;
                case "SaveDispatchData"://保存工步派工信息
                    SaveDispatchData(context);
                    break;
                //工步派工修改
                case "GetRBDispatchModifyDatas"://获取可修改的工步派工信息
                    GetRBDispatchModifyDatas(context);
                    break;
                case "GetEmployeeDatas"://获取批次派工班组下的人员
                    GetEmployeeDatas(context);
                    break;
                case "SaveModifyDispatchData"://保存派工人员修改
                    SaveModifyDispatchData(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "出错了：" + e.Message, Result = false }));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// 保存需修改的派工数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveModifyDispatchData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true,Message = "修改成功" };
        DataTable dtContainer = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["container"].ToString());
        DataTable dtStepInfo = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["stepInfo"].ToString());
        DataTable dtEmployee = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["employee"].ToString());
        if (dtContainer.Rows.Count == 0 || dtStepInfo.Rows.Count == 0 || dtEmployee.Rows.Count == 0)
        {
            result.Result = false; result.Message = "数据过期，请重新查询";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //Task<uMESProcessResult>[] tasks = new Task<uMESProcessResult>[dtContainer.Rows.Count];
        //for (int i = 0; i < dtContainer.Rows.Count; i++)
        //{
        //    tasks[i] = SaveDispatchEmpByContainer(dtContainer.Rows[i], dtStepInfo, dtEmployee);
        //}
        //Task.WaitAll(tasks);
        //foreach (Task item in tasks)
        //{

        //}
        string sql = string.Empty;
        ArrayList sqlList = new ArrayList();
        for (int i = 0; i < dtContainer.Rows.Count; i++)//循环批次
        {
            DataRow container = dtContainer.Rows[i];
            foreach (DataRow stepInfo in dtStepInfo.Rows)//循环工步
            {
                sql = "SELECT 1 FROM containerstepworkreport2 csw WHERE csw.containerid = '{0}' AND csw.stepinfoid = '{1}' AND csw.isuse = 0";
                sql = string.Format(sql, container["containerid"].ToString(), stepInfo["stepInfoId"].ToString());
                if (DatabaseHelper.GetSingle(sql) != null)
                {
                    result.Result = false;
                    result.Message = string.Format("批次：{0}工步{1}存在报工，不可修改", container["containername"].ToString(), stepInfo["stepName"].ToString());
                    break;
                }
                sql = "SELECT csd.containerstepdispatchid FROM containerstepdispatch2 csd WHERE csd.containerid = '{0}' AND csd.stepinfoid = '{1}' AND csd.isuse = 0";
                sql = string.Format(sql, container["containerid"].ToString(), stepInfo["stepInfoId"].ToString());
                DataTable dtDis = DatabaseHelper.Query_ReturnDatTable(sql);
                for (int k = 0; k < dtDis.Rows.Count; k++)//循环工步的所有派工
                {
                    sqlList.Add(string.Format("DELETE containerstepdispatchdetail2 csdd WHERE csdd.containerstepdispatchid = '{0}'", dtDis.Rows[k]["containerstepdispatchid"].ToString()));
                    sqlList.Add(string.Format("UPDATE containerstepdispatch2 csd SET csd.workerid = NULL WHERE csd.containerstepdispatchid = '{0}'", dtDis.Rows[k]["containerstepdispatchid"].ToString()));
                    foreach (DataRow emp in dtEmployee.Rows)//循环添加人员，将人员添加到派工明细
                    {
                        sqlList.Add(string.Format("INSERT INTO containerstepdispatchdetail2(containerstepdispatchid,workerid,createdate) VALUES('{0}','{1}',sysdate)", dtDis.Rows[k]["containerstepdispatchid"].ToString(), emp["employeeid"].ToString()));
                    }
                }
            }
            if (!result.Result)
            {
                break;
            }
        }
        if (result.Result)
        {
            DatabaseHelper.ExecuteSqlTran(sqlList);
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    //public uMESProcessResult SaveDispatchEmpByContainer(DataRow container, DataTable dtStepInfo, DataTable dtEmployee)
    //{
    //    uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "修改成功" };
    //    string sql = string.Empty;
    //    ArrayList sqlList = new ArrayList();
    //    foreach (DataRow stepInfo in dtStepInfo.Rows)
    //    {
    //        sql = "SELECT 1 FROM containerstepworkreport2 csw WHERE csw.containerid = c.containerid AND csw.stepinfoid = s.stepinfoid AND csw.isuse = 0";
    //        if (DatabaseHelper.GetSingle(sql) != null)
    //        {
    //            result.Result = false;
    //            result.Message = string.Format("批次：{0}工步{1}存在报工，不可修改",);
    //            break;
    //        }
    //        sql = "SELECT csd.containerstepdispatchid FROM containerstepdispatch2 csd WHERE csd.containerid = '{0}' AND csd.stepinfoid = '{1}' AND csd.isuse = 0";
    //        sql = string.Format(sql, container[""].ToString(), stepInfo[""].ToString());
    //        DataTable dtDis = DatabaseHelper.Query_ReturnDatTable(sql);
    //        for (int i = 0; i < dtDis.Rows.Count; i++)
    //        {
    //            sqlList.Add(string.Format("DELETE containerstepdispatchdetail2 csdd WHERE csdd.containerstepdispatchid = '{0}'", dtDis.Rows[i]["containerstepdispatchid"].ToString()));
    //            sqlList.Add(string.Format("UPDATE containerstepdispatch2 csd SET csd.workerid IS NULL WHERE csd.containerstepdispatchid = '{0}'", dtDis.Rows[i]["containerstepdispatchid"].ToString()));
    //            foreach (DataRow emp in dtEmployee.Rows)
    //            {
    //                sqlList.Add(string.Format("INSERT INTO containerstepdispatchdetail2(containerstepdispatchid,workerid,createdate) VALUES('{0}','{1}',sysdate)", dtDis.Rows[i]["containerstepdispatchid"].ToString(), emp["employeeid"].ToString()));
    //            }

    //        }
    //    }
    //    return result;
    //}

    /// <summary>
    /// 获取派工班组下的人员
    /// </summary>
    /// <param name="context"></param>
    public void GetEmployeeDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string containerID = context.Request.Form["containerid"].ToString();
        string workflowstepID = context.Request.Form["workflowstepId"].ToString();
        string employeeName = context.Request.Form["employeeName"].ToString();
        if (string.IsNullOrWhiteSpace(containerID) || string.IsNullOrWhiteSpace(workflowstepID))
        {
            result.Result = false; result.Message = "批次数据出错，请检查批次数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string sql = string.Format(@"SELECT e.employeeid,e.fullname,e.employeename FROM containerstepdispatch csd 
                       LEFT JOIN teamemployee te ON te.teamid = csd.teamid
                       LEFT JOIN employee e ON e.employeeid = te.employeeid
                       WHERE csd.containerid = '{0}' AND csd.workflowstepid = '{1}' AND csd.isuse = 0 {2}",
                       containerID, workflowstepID, string.IsNullOrWhiteSpace(employeeName) ? "" : string.Format(" AND e.fullname like '%{0}%'", employeeName));
        DataTable dtEmp = DatabaseHelper.Query_ReturnDatTable(sql);
        result.DBTable = dtEmp;
        if (dtEmp.Rows.Count == 0)
        {
            result.Result = false; result.Message = "工序派工的班组下未找到人员信息";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取可修改的派工数据
    /// </summary>
    /// <param name="context"></param>
    public void GetRBDispatchModifyDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string scanContainer = context.Request.Form["scanContainer"].ToString();
        string containerName = context.Request.Form["containerName"].ToString();
        if (string.IsNullOrWhiteSpace(scanContainer) && string.IsNullOrWhiteSpace(containerName))
        {
            result.Result = false; result.Message = "请输入查询条件";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (!string.IsNullOrWhiteSpace(scanContainer))//如果存在扫描批次，则以扫描为准
        {
            containerName = uMESCommonbusiness.ContainerScan(scanContainer);
        }
        //查询批次信息
        string sql = string.Format(@"SELECT c1.containername,c1.containerid,c1.qty,c1.mfgordername,cb.containercombinatename combinatename,
                        c1.workflowstepname,c1.originalstartdate createdate,c1.workflowstepid
                        FROM containercurrentinfo c 
                        LEFT JOIN containercombinate cb ON cb.containerid = c.containerid
                        LEFT JOIN containercombinate cbb ON cbb.containercombinatename = cb.containercombinatename
                        LEFT JOIN containercurrentinfo c1 ON c1.containerid = (CASE WHEN cb.containercombinateid IS NULL THEN c.containerid ELSE cbb.containerid END)
                        WHERE c.containername = '{0}' AND c1.containerstatus = 1", containerName);
        DataTable dtContainer = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtContainer.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未找到批次";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        sql = @"SELECT s.stepinfoid,s.stepno,s.description,c.containerid,'' reportEmp FROM containercurrentinfo c 
                LEFT JOIN stepinfo s ON s.workflowstepid = c.workflowstepid
                WHERE c.containername = '{0}' 
                AND EXISTS (SELECT 1 FROM containerstepdispatch2 csd WHERE csd.containerid = c.containerid AND csd.stepinfoid = s.stepinfoid AND csd.isuse = 0)
                AND NOT EXISTS (SELECT 1 FROM containerstepworkreport2 csw WHERE csw.containerid = c.containerid AND csw.stepinfoid = s.stepinfoid AND csw.isuse = 0)
                ORDER BY s.stepseq";
        sql = string.Format(sql, containerName);
        DataTable dtStepInfo = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtStepInfo.Rows.Count == 0)
        {
            result.Result = false; result.Message = "不存在可修改的派工工步";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //查询工步报工人
        sql = @"SELECT to_char(wm_concat(e.fullname)) fullname FROM containerstepdispatch2 csd 
                LEFT JOIN containerstepdispatchdetail2 csdd ON csdd.containerstepdispatchid = csd.containerstepdispatchid
                LEFT JOIN employee e ON e.employeeid = CASE WHEN csd.workerid IS NULL THEN csdd.workerid ELSE csd.workerid END
                WHERE csd.containerid = '{0}' AND csd.stepinfoid = '{1}' AND csd.isuse = 0";
        foreach (DataRow item in dtStepInfo.Rows)
        {
            DataTable dtRes = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, item["containerid"].ToString(), item["stepinfoid"].ToString()));
            item["reportEmp"] = dtRes.Rows[0]["fullname"].ToString();
        }
        dtContainer.TableName = "dtContainer";
        dtStepInfo.TableName = "dtStepInfo";
        result.DBDataSet.Tables.Add(dtContainer);
        result.DBDataSet.Tables.Add(dtStepInfo);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取工步派工主数据列表
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerStepInfoDispatchList(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;
        Dictionary<string, string> para = new Dictionary<string, string>();

        para.Add("CurrentPageIndex", context.Request.Form["pageNumber"].ToString());//页码
        para.Add("PageSize", context.Request.Form["pageSize"].ToString());//每页页数
        if (!string.IsNullOrWhiteSpace(context.Request.Form["containerName"].ToString()))
        {
            para.Add("ContainerName", context.Request.Form["containerName"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request.Form["scanMfgorderName"].ToString()))
        {
            para.Add("mfgOrderName", context.Request.Form["scanMfgorderName"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request.Form["productName"].ToString()))
        {
            para.Add("ProductName", context.Request.Form["productName"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request.Form["specNo"].ToString()))
        {
            para.Add("StepNo", context.Request.Form["specNo"].ToString());
        }
        if (!string.IsNullOrWhiteSpace(context.Request.Form["combinateName"].ToString()))
        {
            para.Add("CombinateName", context.Request.Form["combinateName"].ToString());
        }

        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("WorkCenterID", m_UserInfo.WorkCenterID);
        if (!string.IsNullOrWhiteSpace(context.Request.Form["scanContainerName"]))
        {
            var containerScan = context.Request.Form["scanContainerName"].ToString(); var tempContainerName = "";
            para.Add("ScanContainerName", context.Request.Form["scanContainerName"].ToString());
            para["ScanContainerName"] = uMESCommonbusiness.GetScanContainerInfoReturnData(ref containerScan, ref tempContainerName);
            para["ContainerType"] = containerScan.Split(',').First();
        }
        result = uMESDispatchbusiness.GetRBContainerStepInfoDispatchList(para);
        //result = uMESDispatchbusiness.GetContainerStepInfoDispatchList(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取热表批次详细
    /// </summary>
    /// <param name="context"></param>
    public void GetRBContainerDetails(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ContainerID", context.Request["containerID"].ToString());
        para.Add("ProductBatch", context.Request["productBatch"].ToString());
        var dt = uMESDispatchbusiness.GetRBContainerStepInfoDisDetail(para);
        result.Result = true;
        result.DBTable = dt;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取批次详细（未启用）
    /// </summary>
    /// <param name="context"></param>
    public void GetContainerDetails(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable paramDt = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["params"].ToString());
        DataRow paramRow = paramDt.Rows[0];
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("TogatherFlag", paramRow["togatherFlag"].ToString());
        para.Add("ProductID", paramRow["productID"].ToString());
        para.Add("WorkflowStepID", paramRow["workflowStepID"].ToString());
        para.Add("WorkflowID", paramRow["WorkflowID"].ToString());
        para.Add("MfgOrderName", paramRow["mfgOrderName"].ToString());
        para.Add("ContainerType", paramRow["containerType"].ToString());
        para.Add("ContainerNo", paramRow["containerNo"].ToString());
        para.Add("FactoryID", m_UserInfo.FactoryID);
        para.Add("WorkCenterID", m_UserInfo.WorkCenterID);
        var dt = uMESDispatchbusiness.GetContainerStepInfoDisDetail(para);
        result.Result = true;
        result.DBTable = dt;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取派工弹窗页面初始化数据
    /// </summary>
    /// <param name="context"></param>
    public void GetInitData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtContainers = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["containers"].ToString());
        if (m_UserInfo == null || dtContainers == null || dtContainers.Rows.Count == 0)
        {
            result.Result = false; result.Message = "缓存过期，请刷新后再试";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string msg = "";
        DataTable dtContainerNew = dtContainers.Clone();
        foreach (DataRow item in dtContainers.Rows)
        {
            if (dtContainerNew.Select(string.Format("ContainerID='{0}'", item["ContainerID"].ToString())).Length == 0)
            {
                dtContainerNew.Rows.Add(item.ItemArray);
                if (!uMESDispatchbusiness.IsVaildSeqForStepInfo(item["ContainerID"].ToString(), item["WorkflowstepID"].ToString(), ref msg))
                {
                    result.Result = false; result.Message = msg;
                    break;
                }
            }
        }
        if (!result.Result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DataSet dtSet = new DataSet();
        //最新的批次
        dtContainerNew.TableName = "dtContainerNew";
        dtSet.Tables.Add(dtContainerNew);
        //获取零件序号列表
        DataTable childDt = new DataTable();
        foreach (DataRow item in dtContainerNew.Rows)
        {
            DataTable dt = uMESCommonbusiness.GetContainerInfoByPerContianerID(item["ContainerID"].ToString());
            childDt.Merge(dt);
        }
        childDt.TableName = "childDt";
        dtSet.Tables.Add(childDt);
        //获取班组下拉数据
        DataTable dt_team = uMESCommonbusiness.GetTeam(m_UserInfo.WorkCenterID);
        DataRow drteam = dt_team.NewRow();
        drteam["TEAMID"] = "";
        drteam["TEAMNAME"] = "请选择";
        dt_team.Rows.InsertAt(drteam, 0);//插入到第一行
        drteam = dt_team.NewRow();
        drteam["TEAMID"] = "0";
        drteam["TEAMNAME"] = "其他";
        dt_team.Rows.Add(drteam);
        string strAttributes = uMESCommonbusiness.GetEnterpriseAttributes("工区长角色");
        if (strAttributes == "")
        {
            strAttributes = "DispatchTFW";
        }
        if (!m_UserInfo.Roles.Contains(strAttributes))
        {
            DataRow drs = dt_team.Select(string.Format("TeamID = '{0}'", m_UserInfo.TeamID)).FirstOrDefault();
            dt_team.Rows[0].ItemArray = drs.ItemArray;//将该员工对应的班组放在第一个并默认选中
            dt_team.Rows.Remove(drs);
            string strValue_ = uMESCommonbusiness.GetFatoryAttributes(m_UserInfo.FactoryID, "多人派工"); //获取工厂是否多人派工 燃烧不修改不可以派给其他班组
            if (strValue_ == "是")
            {
                int len = dt_team.Rows.Count - 1;
                for (int i = 0; i < len; i++)
                {
                    dt_team.Rows.RemoveAt(1);//删除第一条以外的所有行，确保只有一个班组
                }
            }
        }
        dt_team.TableName = "dtTeam";
        dtSet.Tables.Add(dt_team);
        //获取工步
        DataTable dtStepInfo = uMESDispatchbusiness.GetStepInfoListByWorkflowStep(dtContainers.Rows[0]["ContainerID"].ToString(), dtContainers.Rows[0]["WorkflowstepID"].ToString());
        dtStepInfo.TableName = "dtStepInfo";
        dtSet.Tables.Add(dtStepInfo);
        //获取当前工序后的所有工序（不用获取所有工序）
        //string strSequence = dtContainers.Rows[0]["Sequence"].ToString();
        //string strWorkflowid = dtContainers.Rows[0]["WorkflowID"].ToString();
        //int intWIPQty = Convert.ToInt32(dtContainers.Rows[0]["WipQty"].ToString());
        //string strContainerIDs = string.Empty;
        //DataTable workStepDT = GetWorkflowDT(ref strContainerIDs, m_UserInfo, dtContainers);
        //Dictionary<string, string> isPara = new Dictionary<string, string>();
        //isPara["ContainerID"] = strContainerIDs;
        //isPara["WorkCenterID"] = m_UserInfo.WorkCenterID;
        //isPara["FactoryID"] = m_UserInfo.FactoryID;
        //isPara["Sequence"] = strSequence;
        //DataTable workCenterDispach = uMESDispatchbusiness.GetWorkCenterORShipInfo(isPara, 0);
        //DataTable shipInfo = uMESDispatchbusiness.GetWorkCenterORShipInfo(isPara, 1);
        //string str_ContainerID = "";
        //if (dtContainers.Rows[0]["ContainerType"].ToString() == "7")
        //{
        //    foreach (DataRow item in dtContainers.Rows)
        //    {
        //        if (str_ContainerID.Length > 0)
        //        {
        //            str_ContainerID += " OR ";
        //        }
        //        str_ContainerID += " CC.CONTAINERID = '" + item["ContainerID"] + "'";
        //    }
        //}
        //else
        //{
        //    str_ContainerID = " CC.CONTAINERID ='" + dtContainers.Rows[0]["ContainerID"].ToString() + "'";
        //}
        //DataTable dt_commission = m_commissioning.GetCommissionProcess(ref str_ContainerID); //外委工序表
        //if (shipInfo.Rows.Count > 0) //只显示转工的工序
        //{
        //    foreach (DataRow dt in workStepDT.Rows)
        //    {
        //        if (shipInfo.Rows[0]["STEPTYPE"].ToString() == "2")
        //        { //转工的子工艺
        //            continue;
        //        }
        //        if (int.Parse(shipInfo.Compute("COUNT(WORKFLOWSTEPID)", String.Format("WORKFLOWSTEPID='{0}'", dt["WORKFLOWSTEPID"].ToString())).ToString()) == 0)
        //        {
        //            dt.Delete();
        //        }
        //    }
        //    workStepDT.AcceptChanges();
        //    ClearNoUseWorkflowStepID(ref workStepDT, dt_commission, new DataTable(), new DataTable(), new DataTable(), new DataTable(), "Dispatch");
        //}
        //else
        //{
        //    DataTable dt_ship = m_ontainerShipObject.GetShipWorkflowStepIDs(str_ContainerID); //临时转工工序表
        //    DataTable newdt = uMESCommonbusiness.GetContainerInfobyContainerName(dtContainers.Rows[0]["ContainerName"].ToString()); //根据批次号获取批次的factoryID
        //    DataTable dt_ControlCodeAndLastCheck = uMESCommonbusiness.GetWorkFlowStepsWithSpceControlCodeAndCheckStep(strWorkflowid, newdt.Rows[0]["FACTORYID"].ToString()); //固定外委或固定转工或检验工序表
        //    //增加临时取消自动转工或外委逻辑
        //    DataTable dt_ControlCodeAndLastCheck2 = dt_ControlCodeAndLastCheck.Clone();
        //    Dictionary<string, string> temPara = new Dictionary<string, string>();
        //    temPara["ContainerIDsOr"] = str_ContainerID.Replace("CC", "csn");
        //    foreach (DataRow shipCommison in dt_ControlCodeAndLastCheck.Rows)
        //    {
        //        temPara["CheckedWorkflowStepID"] = shipCommison["WorkflowStepID"].ToString();
        //        if (m_ontainerShipObject.GetCancleAutoShipOrComission(temPara).Rows.Count == 0)
        //        {
        //            dt_ControlCodeAndLastCheck2.ImportRow(shipCommison);
        //        }
        //    }
        //    workStepDT.AcceptChanges();
        //    ClearNoUseWorkflowStepID(ref workStepDT, dt_commission, dt_ship, new DataTable(), dt_ControlCodeAndLastCheck2, new DataTable(), "Dispatch");
        //}
        //if (workCenterDispach.Rows.Count > 0) //只显示工区协作的工序           
        //{
        //    workStepDT.AcceptChanges();
        //    foreach (DataRow item in workStepDT.Rows)
        //    {
        //        if (int.Parse(workCenterDispach.Compute("COUNT(WORKFLOWSTEPID)", string.Format("WORKFLOWSTEPID='{0}'", item["WORKFLOWSTEPID"].ToString())).ToString()) == 0)
        //        {
        //            if (workCenterDispach.Rows[0]["workcenterid"].ToString() == m_UserInfo.WorkCenterID)
        //            { //如果是原来的工区 ’add Wangjh 2017-7-11
        //                continue;
        //            }
        //            else if (workCenterDispach.Rows[0]["Toworkcenterid"].ToString() == m_UserInfo.WorkCenterID)
        //            { //如果是协作的工区
        //                item.Delete();
        //                continue;
        //            }
        //        }
        //        if (workCenterDispach.Rows[0]["workcenterid"].ToString() == m_UserInfo.WorkCenterID)
        //        { //如果是原来的工区 ’add Wangjh 2017-7-11
        //            item.Delete(); //这里隐藏存在工区协作的
        //        }
        //    }
        //}
        //workStepDT.AcceptChanges();
        //workStepDT.TableName = "dtWorkStep";
        //dtSet.Tables.Add(workStepDT);
        //优先级
        DataTable natdt = uMESCommonbusiness.GetNaturalNumberDatatable(uLMS_CommonFunction.GetNaturalNumberSql(1, 9));
        natdt.TableName = "natdt";
        dtSet.Tables.Add(natdt);
        result.DBDataSet = dtSet;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取工艺工序信息
    /// </summary>
    /// <param name="strContainerIDs"></param>
    /// <param name="userInfo"></param>
    /// <param name="containerInfo"></param>
    /// <param name="containerIndex"></param>
    /// <returns></returns>
    private DataTable GetWorkflowDT(ref string strContainerIDs, CurrentUserInfo userInfo, DataTable containerInfo)
    {
        // bool notDelete = false;
        if (strContainerIDs == "strnull")
        {
            // notDelete = true;
            strContainerIDs = "";
        }
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("WorkflowID", containerInfo.Rows[0]["WorkflowID"].ToString());
        para.Add("Sequence", containerInfo.Rows[0]["Sequence"].ToString());
        string strSelectvalue = uMESCommonbusiness.GetFatoryAttributes(userInfo.FactoryID, "工序关联工区班组"); //获取工厂报工是否工序工区派工
        if (strSelectvalue == "是")
        {
            para.Add("StepDispatch", "");
            para.Add("ContainerID", containerInfo.Rows[0]["ContainerID"].ToString());
            para.Add("TeamID", userInfo.TeamID);
        }
        DataTable dtWorkflow = uMESCommonbusiness.GetWorkFlowStepsWithoutSelf(para); //获取当前工序及以后的所有工序
        foreach (DataRow item in containerInfo.Rows)
        {
            strContainerIDs = String.Format("{0},'{1}'", strContainerIDs, item["ContainerID"].ToString());
        }
        if (strContainerIDs.Length > 0)
        {
            strContainerIDs = strContainerIDs.Substring(1);
        }
        //处理以及完工的工序就不再显示
        DataTable IsCompleted_dt = uMESDispatchbusiness.GetIsCompletedStep(strContainerIDs, containerInfo.Rows[0]["WorkflowID"].ToString());
        if (IsCompleted_dt.Rows.Count > 0)
        {
            foreach (DataRow cr in IsCompleted_dt.Rows)
            {
                foreach (DataRow wf in dtWorkflow.Rows)
                {
                    if (wf["WORKFLOWSTEPID"].ToString() == cr["WORKFLOWSTEPID"].ToString())
                    {
                        wf.Delete();
                        break;
                    }
                }
                dtWorkflow.AcceptChanges();
            }
        }
        //检查工序是否已经派完工（派完工则不显示）
        foreach (DataRow item in dtWorkflow.Rows)
        {
            DataTable dt = uMESDispatchbusiness.GetStepInfoListByWorkflowStep(containerInfo.Rows[0]["ContainerID"].ToString(), item["WorkflowStepId"].ToString());
            if (dt.Rows.Count == 0)//如果工序没有可以派工的工步，则该工序不显示
            {
                item.Delete();
            }
        }
        dtWorkflow.AcceptChanges();
        //para.Clear();
        //para.Add("WorkflowID", containerInfo.Rows[0]["WorkflowID"].ToString());
        //para.Add("Sequence", containerInfo.Rows[0]["Sequence"].ToString());
        //para.Add("ContainerIDs", strContainerIDs);
        //DataTable dtStepDispatch = uMESDispatchbusiness.GetStepDispatchSpecList(para); //获取批次当前序及之后已经派工的信息
        //dtWorkflow.Columns.Add("CanDispatchQty"); //在所有工序表中添加两行 可派数以及已经派工的工人ID
        //dtWorkflow.Columns.Add("DispatchWorkers");
        //DataTable dtworker = uMESDispatchbusiness.GetDispatchWorkerList(para);//根据containerid获取该批次已经派工的
        //for (int i = 0; i < dtWorkflow.Rows.Count; i++)
        //{
        //    DataRow drStep = dtWorkflow.Rows[i];
        //    string objQty = dtStepDispatch.Compute("SUM(DISQTY)", String.Format("WORKFLOWSTEPID='{0}'", drStep["WORKFLOWSTEPID"])).ToString();
        //    if (string.IsNullOrWhiteSpace(objQty))
        //    {
        //        drStep["CanDispatchQty"] = containerInfo.Rows[0]["WipQty"];
        //        continue;
        //    }
        //    if (Convert.ToInt32(containerInfo.Rows[0]["WipQty"].ToString()) > Convert.ToInt32(objQty))
        //    {
        //        int intCanQty = Convert.ToInt32(containerInfo.Rows[0]["WipQty"].ToString()) - Convert.ToInt32(objQty);
        //        drStep["CanDispatchQty"] = intCanQty;
        //    }
        //    else
        //    {
        //        if (!notDelete)
        //        {
        //            drStep.Delete();
        //            continue;
        //        }
        //    }
        //    DataRow[] drs = dtworker.Select(String.Format("WORKFLOWSTEPID='{0}'", drStep["WORKFLOWSTEPID"]));
        //    string strDispatchWorkers = "";
        //    foreach (DataRow dr in drs)
        //    {
        //        if (dr["CSD_WORKERID"] != null)
        //        {
        //            strDispatchWorkers = String.Format("{0},{1}", strDispatchWorkers, dr["CSD_WORKERID"]); //单人派工
        //        }
        //        else
        //        {
        //            strDispatchWorkers = String.Format("{0},{1}", strDispatchWorkers, dr["CSDT_WORKERID"]); //多人派工
        //        }
        //    }
        //    drStep["DispatchWorkers"] = strDispatchWorkers;
        //}
        //dtWorkflow.AcceptChanges();
        return dtWorkflow;
    }
    /// <summary>
    /// 派工、外委、工区协助等工序排除
    /// </summary>
    /// <param name="workStepDT"></param>
    /// <param name="dt_commission"></param>
    /// <param name="dt_ship"></param>
    /// <param name="dt_workCenter"></param>
    /// <param name="dt_ControlCodeAndLastCheck"></param>
    /// <param name="dt_Dispatched"></param>
    /// <param name="key"></param>
    private void ClearNoUseWorkflowStepID(ref DataTable workStepDT, DataTable dt_commission, DataTable dt_ship, DataTable dt_workCenter, DataTable dt_ControlCodeAndLastCheck, DataTable dt_Dispatched, string key)
    {
        bool ishidden = false;
        foreach (DataRow dt in workStepDT.Rows)
        {
            if (key != "Dispatch")
            {
                if (dt_Dispatched.Rows.Count > 0)
                {
                    foreach (DataRow row in dt_Dispatched.Rows)
                    {
                        if (row["WORKFLOWSTEPID"].ToString() == dt["WorkFlowStepID"].ToString())
                        {
                            dt.Delete();
                            ishidden = true;
                            break;
                        }
                    }
                }
                if (ishidden)
                {
                    continue;
                }
            }
            if (key != "Commission")
            {
                if (dt_commission.Rows.Count > 0)
                {
                    foreach (DataRow row in dt_commission.Rows)
                    {
                        if (Convert.ToInt32(dt["Sequence"].ToString()) >= Convert.ToInt32(row["FIRSTSEQUENCE"].ToString()) && Convert.ToInt32(dt["Sequence"]) < Convert.ToInt32(row["LASTSEQUENCE"].ToString()))
                        {
                            if (row["WORKFLOWSTEPID"].ToString() == dt["WorkFlowStepID"].ToString())
                            {
                                dt.Delete();
                            }
                        }
                    }
                }
            }
            ishidden = false;
            if (key != "Ship")
            {
                if (dt_ship.Rows.Count > 0)
                {
                    foreach (DataRow row in dt_ship.Rows)
                    {
                        if (row["WORKFLOWSTEPID"].ToString() == dt["WorkFlowStepID"].ToString())
                        {
                            dt.Delete();
                            ishidden = true;
                            break;
                        }
                    }
                }
                if (ishidden)
                {
                    continue;
                }
            }
            ishidden = false;
            if (key != "workCenter")
            {
                if (dt_workCenter.Rows.Count > 0)
                {
                    foreach (DataRow row in dt_workCenter.Rows)
                    {
                        if (row["WORKFLOWSTEPID"].ToString() == dt["WorkFlowStepID"].ToString())
                        {
                            dt.Delete();
                            ishidden = true;
                            break;
                        }
                    }
                }
                if (ishidden)
                {
                    continue;
                }
            }
            if (dt_ControlCodeAndLastCheck.Rows.Count > 0)
            {
                foreach (DataRow row in dt_ControlCodeAndLastCheck.Rows)
                {
                    if (row["WORKFLOWSTEPID"].ToString() == dt["WorkFlowStepID"].ToString())
                    {
                        dt.Delete();
                        break;
                    }
                }
            }
        }
    }
    /// <summary>
    /// 获取工步列表数据
    /// </summary>
    /// <param name="context"></param>
    public void GetStepInfoList(HttpContext context)
    {
        string workflowstepId = context.Request.Form["workflowstepId"].ToString();
        string containerId = context.Request.Form["containerId"].ToString();
        DataTable dt = uMESDispatchbusiness.GetStepInfoListByWorkflowStep(containerId, workflowstepId);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, DBTable = dt }));
    }

    /// <summary>
    /// 选择班组后，获取操作工
    /// update:wangjh 20220302 优化增加人员设备查询
    /// </summary>
    /// <param name="context"></param>
    public void GetOperator(HttpContext context)
    {
        string strSelectValue = context.Request.Form["teamID"].ToString();
        DataTable dt = new DataTable();
        Dictionary<string, string> para = new Dictionary<string, string>();
        if (strSelectValue == "0")
        {
            string strAttributes = uMESCommonbusiness.GetEnterpriseAttributes("工区长角色");

            para.Add("RoleName", strAttributes);
            para.Add("WorkCenterID", m_UserInfo.WorkCenterID);
            para.Add("FactoryID", m_UserInfo.FactoryID);
            dt = uMESCommonbusiness.GetEmployeeRoles(para);
            dt.Columns.Add("EMPLOYEEID");

            foreach (DataRow item in dt.Rows)
            {
                item["EMPLOYEEID"] = item["CHECKERID"];
            }

            dt.AcceptChanges();
        }
        else
        {
            dt = uMESCommonbusiness.GetEmployeeInfoByTeamId(strSelectValue);
        }

        dt.Columns.Add("RESOURCES");//add:Wangjh 20220302 
        foreach (DataRow item in dt.Rows)
        {
            var temp = uMESCommonbusiness.GetResourceDefByemployeeid(" em.employeeid='" + item["EMPLOYEEID"].ToString() + "'");
            var resources = temp.DefaultView.ToTable(true, "RESNAME", "resourceid");
            item["Resources"] = JsonConvert.SerializeObject(resources);
        }

        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, DBTable = dt }));
    }
    /// <summary>
    /// 选择员工后,获取设备资源
    /// </summary>
    /// <param name="context"></param>
    public void GetResource(HttpContext context)
    {
        string stremployeeids = context.Request.Form["employeeids"].ToString();
        DataTable dt = uMESCommonbusiness.GetResourceDefByemployeeid(stremployeeids);
        string[] array = new string[2];
        array[0] = "RESNAME";
        array[1] = "resourceid";
        DataTable newdt = dt.DefaultView.ToTable(true, array);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "获取成功", Result = true, DBTable = newdt }));
    }

    /// <summary>
    /// 保存工步派工数据
    /// </summary>
    /// <param name="context"></param>
    private void SaveDispatchData(HttpContext context)
    {
        DataTable dtContainers = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["dtContainers"].ToString());//批次列表
        DataTable stepInfoDatas = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["stepInfoDatas"].ToString());//工序列表
        DataTable operatorDatas = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["operatorDatas"].ToString());//操作工列表
        if (dtContainers.Rows.Count == 0 || stepInfoDatas.Rows.Count == 0 || operatorDatas.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "数据过期", Result = false }));
            return;
        }
        string teamId = context.Request.Form["teamId"].ToString();//班组
        string resource = context.Request.Form["resource"].ToString();//设备
        string dispatchQty = context.Request.Form["dispatchQty"].ToString();//派工数量
        string startDate = context.Request.Form["startDate"].ToString();//开始日期
        string endDate = context.Request.Form["endDate"].ToString();//结束日期
        if (DateTime.Parse(startDate) < DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "开始日期不能小于当前日期", Result = false }));
            return;
        }
        if (DateTime.Parse(startDate) > DateTime.Parse(endDate))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "开始日期不能大于结束日期", Result = false }));
            return;
        }
        string priorityCode = context.Request.Form["priorityCode"].ToString();//优先级编号
        string currStepId = dtContainers.Rows[0]["WORKFLOWSTEPID"].ToString();//当前工序
        //int disPatchType = 1;
        //foreach (DataRow step in stepInfoDatas.Rows)
        //{
        //    if (step["WORKFLOWSTEPID"].ToString() == currStepId)
        //    {
        //        disPatchType = 2;
        //        break;
        //    }
        //}
        bool isError = false;
        string msg = "派工成功";
        DataTable dtWorkSteP = uMESDispatchbusiness.GetStepInfoListByWorkflowStep(dtContainers.Rows[0]["CONTAINERID"].ToString(), stepInfoDatas.Rows[0]["WORKFLOWSTEPID"].ToString());
        foreach (DataRow dw in dtWorkSteP.Rows)
        {
            if (isError) { break; }
            foreach (DataRow ds in stepInfoDatas.Rows)
            {
                if (ds["stepinfoid"].ToString() == dw["stepinfoid"].ToString())
                {
                    if (Convert.ToInt32(dispatchQty) > Convert.ToInt32(dw["candisqty"].ToString()))
                    {
                        isError = true;
                        msg = "派工数量大于可派数量或可派数已改变，请重新填写或者刷新页面";
                        break;
                    }
                }
            }
        }
        List<ContainerStepDispatchDTO> dtoList = new List<ContainerStepDispatchDTO>();
        List<object[]> sqlStringList = new List<object[]>();
        if (!isError) //验证没问题，则派工
        {
            for (int i = 0; i < dtContainers.Rows.Count; i++)
            {
                string strContainerId = dtContainers.Rows[i]["CONTAINERID"].ToString();
                foreach (DataRow ds in stepInfoDatas.Rows)
                {
                    ContainerStepDispatchDTO newDTO = new ContainerStepDispatchDTO();
                    newDTO.ContainerID = strContainerId;
                    newDTO.FactoryID = m_UserInfo.FactoryID;
                    newDTO.WorkCenterID = m_UserInfo.WorkCenterID;
                    newDTO.TeamID = teamId;
                    newDTO.WorkflowstepID = ds["WORKFLOWSTEPID"].ToString();
                    newDTO.stepID = ds["StepInfoID"].ToString();//工步ID
                    newDTO.ResourceID = resource;
                    newDTO.Qty = Convert.ToInt32(dispatchQty);//派工数量
                    newDTO.PlannedStartDate = Convert.ToDateTime(startDate);
                    newDTO.PlannedFinishDate = Convert.ToDateTime(endDate);
                    newDTO.ContainerStepDispatchID = Guid.NewGuid().ToString();
                    newDTO.EmployeeID = m_UserInfo.EmployeeID.ToString();
                    newDTO.PriorityCode = int.Parse(priorityCode);
                    newDTO.WorkerID = operatorDatas.Rows.Count > 1 ? "" : operatorDatas.Rows[0]["EMPLOYEEID"].ToString();
                    //存在相同的批次、工序、工步，则不派工
                    if (dtoList.Where(p => p.ContainerID == newDTO.ContainerID && p.WorkflowstepID == newDTO.WorkflowstepID && p.stepID == newDTO.stepID).Count() == 0)
                    {
                        dtoList.Add(newDTO);
                        sqlStringList.Add(uMESDispatchbusiness.FillContainerStepInfoDispatchDataSql(newDTO));
                        if (operatorDatas.Rows.Count > 1)
                        {
                            foreach (DataRow item in operatorDatas.Rows)
                            {
                                sqlStringList.Add(uMESDispatchbusiness.FillStepInfoDispatchDetails(newDTO.ContainerStepDispatchID, item["EMPLOYEEID"].ToString()));
                            }
                        }
                    }
                }
                //sqlStringList.Add(uMESDispatchbusiness.FillUpdateContainerDispatchNum(strContainerId, disPatchType.ToString()));
            }
        }
        if (sqlStringList.Count > 0)
        {
            if (!DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlTran(sqlStringList))
            {
                isError = true;
                msg = "更新批次派工状态出错";
            }
            if (!isError)
            {
                sqlStringList.Clear();
                foreach (DataRow item in dtContainers.Rows)
                {
                    //如果批次的工序下所有工步派工完，则插入工序派工
                    if (uMESDispatchbusiness.IsStepInfoDispatched(item) && !IsExistStepDisInfo(item))
                    {
                        ContainerStepDispatchDTO newDTO = new ContainerStepDispatchDTO();
                        newDTO.ContainerID = item["ContainerID"].ToString();
                        newDTO.FactoryID = m_UserInfo.FactoryID;
                        newDTO.WorkCenterID = m_UserInfo.WorkCenterID;
                        newDTO.TeamID = teamId;
                        newDTO.WorkflowstepID = item["WORKFLOWSTEPID"].ToString();
                        newDTO.ResourceID = resource;
                        newDTO.Qty = int.Parse(item["WipQty"].ToString());//派工数量
                        newDTO.PlannedStartDate = Convert.ToDateTime(startDate);
                        newDTO.PlannedFinishDate = Convert.ToDateTime(endDate);
                        newDTO.ContainerStepDispatchID = Guid.NewGuid().ToString();
                        newDTO.EmployeeID = m_UserInfo.EmployeeID.ToString();
                        newDTO.PriorityCode = int.Parse(priorityCode);
                        newDTO.WorkerID = operatorDatas.Rows.Count > 1 ? "" : operatorDatas.Rows[0]["EMPLOYEEID"].ToString();
                        sqlStringList.Add(uMESDispatchbusiness.FillContainerStepDispatchInfo(newDTO));
                        if (operatorDatas.Rows.Count > 1)
                        {
                            foreach (DataRow item1 in operatorDatas.Rows)
                            {
                                sqlStringList.Add(uMESDispatchbusiness.FillDispatchdetails(newDTO.ContainerStepDispatchID, item1["EMPLOYEEID"].ToString()));
                            }
                        }
                    }
                }
                if (sqlStringList.Count > 0)
                {
                    DatabaseHelper.ExecuteSqlTran(sqlStringList);
                }

                //派工后自动发起工装及辅料准备申请 add zhunan 2023.1.4
                uLMSCommonIBusiness m_Common = uMESBusinessFactory.instance.GetuLMSCommonObject();
                string strAutoArrangement = m_Common.GetFatoryAttributes(m_UserInfo.FactoryID, "派工后工装及辅料准备");
                if (strAutoArrangement == "是")
                {
                    Dictionary<string, string> para = new Dictionary<string, string>();
                    para.Add("EmployeeID", m_UserInfo.EmployeeID.ToString());//申请人
                    para.Add("TeamID", teamId);//班组
                    para.Add("PlannedFinishDate", endDate);//派工结束日期
                    para.Add("arrangementsID2", Guid.NewGuid().ToString());//生产准备ID2，一次申请，所有数据保持一致
                    foreach (DataRow item in dtContainers.Rows)
                    {
                        ArrayList sqlArrangementStringList = new ArrayList();
                        string containerid = item["ContainerID"].ToString();
                        sqlArrangementStringList = uMESDispatchbusiness.SaveSpecArrangementsAfterDispatching(stepInfoDatas, containerid, para);
                        if (sqlArrangementStringList.Count > 0)
                        {
                            DatabaseAccess.DBUtility.DatabaseHelper.ExecuteSqlTran(sqlArrangementStringList);
                        }
                    }
                }
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = msg, Result = !isError }));
    }
    /// <summary>
    /// 是否存在工序派工
    /// </summary>
    /// <param name="dr"></param>
    /// <returns></returns>
    public bool IsExistStepDisInfo(DataRow dr)
    {
        string sql = "SELECT 1 FROM containerstepdispatch csd WHERE csd.containerid = '{0}' AND csd.workflowstepid = '{1}' AND csd.isuse = 0";
        sql = string.Format(sql, dr["ContainerID"].ToString(), dr["WORKFLOWSTEPID"].ToString());
        if (DatabaseHelper.Query_ReturnDatTable(sql).Rows.Count == 0)
        {
            return false;
        }
        return true;
    }
}